import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    book: {},
    cart: [],

  },
  mutations: {//修改state中变量值
    addGoods(state, bk) {
      let index = -1;
      for (let i = 0; i < state.cart.length; i++) {
        if (bk.id === state.cart[i].id) {
          index = i;
          break;
        }
      }
      if (index >= 0) {
        if(state.cart[index].number<bk.pnum){
          state.cart[index].number++;
          state.cart[index].lineTotal += bk.price;
        }else{
            
        }
        
      }
      else {
        bk['number'] = 1;
        bk['lineTotal'] = bk.price;
        state.cart.push(bk);
      }

    },
    refresh(state, params) {
      state.cart[params.index].lineTotal = state.cart[params.index].price * params.val;
      let bk = state.cart[params.index];
      state.cart.splice(params.index, 1, bk)
    },
    delGoods(state, index) {
      state.cart.splice(index, 1);
    }
  },
  actions: {
    addGoods(context, bk) {
      context.commit('addGoods', bk)
    },
    refresh(context, params) {
      context.commit('refresh', params)
    },
    delGoodsByIndex(context, index) {
      context.commit('delGoodsByIndex', index)
    }
  },
  modules: {
  },
  getters: {
    getGoodsCartNumber(state){
      return function(id){
        let index=-1;
        for (let i=0; i< state.cart.length; i++){
            if(id=== state.cart[i].id){
              index=i;
              break;
            }

        }
        if(index>=0){
          return state.cart[index].number;
        }else{
          return 0;
        }
      }
    
    },
    totelPrice(state) {
      let price_total = 0;
      for (let i = 0; i < state.cart.length; i++) {
        price_total +=
          state.cart[i].price * state.cart[i].number;
      }
      return price_total;
    },
    totelNumber(state) {
      let number_total = 0;
      for (let i = 0; i < state.cart.length; i++) {
        number_total +=
          state.cart[i].number;
      }
      return number_total;
    },
  }
})

